<template>
  <view class="container">
    <view class="content">
      <!-- 左侧：药物列表和搜索 -->
      <view class="left-side">
        <view class="search-box">
          <input type="text" placeholder="搜索药物" class="search-input" v-model="searchQuery" />
          <button class="search-button" size="mini" @click="fetchDrugs">搜索</button>
        </view>
        <view class="drug-list">
          <view v-for="drug in filteredDrugs" :key="drug.id" class="drug-item" @click="addDrugToPrescription(drug)">
            <view class="drug-name">{{ drug.product_name }}</view>
            <view class="drug-details">规格ID：{{ drug.spec_id }} |库存：{{ drug.quantity }} | 价格：￥{{ drug.retail_price }} | 规格：{{ drug.spec_name }}</view>
          </view>
        </view>
      </view>

      <!-- 右侧：药方展示 -->
      <view class="right-side">
        <view class="prescription-list">
          <view v-for="item in prescription" :key="item.id" class="prescription-item">
            <view class="item-details">
              <text>{{ item.product_name }}</text>
              <view class="input-group">
                <label>单价：</label>
                <text>￥{{ item.retail_price }}</text>
              </view>
              <view class="input-group">
                <label>数量：</label>
                <view class="item-controls">
                  <button @click="decreaseQuantity(item)" size="mini">-</button>
                  <text>{{ item.quantity }}</text>
                  <button @click="increaseQuantity(item)" size="mini">+</button>
                </view>
              </view>
              <view class="input-group">
                <label>小计：</label>
                <text>￥{{ item.total }}</text>
              </view>
            </view>
            <view class="item-controls">
              <button @click="removeDrugFromPrescription(item)" size="mini">删除</button>
            </view>
          </view>
        </view>
        <view class="order-summary">
          <view class="summary-item">总金额：￥{{ totalAmount }}</view>
        </view>
        <view class="button-group">
          <button class="clear-button" size="mini" @click="clearPrescription">清空药方</button>
          <button class="submit-button" size="mini" @click="openSubmitPopup">提交药方</button>
        </view>
      </view>
    </view>

    <!-- 提交药方弹窗 -->
    <uni-popup ref="submitPopup" type="center">
      <view class="popup-container">
        <h3>提交药方</h3>
        <view class="form-group">
          <label>医生：</label>
          <select v-model="selectedDoctorIndex" class="input-field">
            <option value="" disabled>请选择医生</option>
            <option v-for="doctor in doctors" :key="doctor.id" :value="doctor.id">{{ doctor.name }}</option>
          </select>
        </view>
        <view class="form-group" style="display: flex; align-items: center;">
          <label>会员卡号：</label>
          <input type="text" v-model="memberCard" class="input-field" />
          <button class="search-button" size="mini" @click="searchMember">搜索</button>
        </view>
        <view class="form-group">
          <label>会员：</label>
          <text>{{ memberName }}</text>
        </view>
        <view class="form-group">
          <label>病情描述：</label>
          <textarea v-model="description" class="input-field" maxlength="800"></textarea>
        </view>
        <view class="button-group">
          <button class="submit-button" size="mini" @click="submitPrescription">提交</button>
          <button class="submit-button" size="mini" @click="closeSubmitPopup">取消</button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
export default {
  data() {
    return {
      searchQuery: '',
      drugs: [],
      filteredDrugs: [],
      prescription: [],
      mainAccountId: '', // 示例主账号ID
      shopId: '', // 示例门店ID
      selectedDoctorIndex: '', // 默认选择的医生索引
      doctors: [], // 医生列表
      memberCard: '', // 会员卡号
      memberName: '', // 会员名称
      description: '', // 病情描述
      userInfo: {}
    };
  },
  computed: {
    totalAmount() {
      return this.prescription.reduce((sum, item) => sum + Number(item.total), 0).toFixed(2);
    }
  },
  methods: {
    async fetchDrugs() {
      const res = await this.$myRuquest({
        url: '/index/plugin.orders/getStock',
        method: 'GET',
        data: {
          shop_id: this.userInfo.shop_id,
          main_account_id: this.userInfo.user_id,
          search_query: this.searchQuery
        }
      });
      if (res.data.code === 200) {
        this.drugs = res.data.data;
        this.filteredDrugs = this.drugs;
      } else {
        uni.showToast({
          title: '获取药物列表失败',
          icon: 'none',
          duration: 2000
        });
      }
    },
    async fetchDoctors() {
      const res = await this.$myRuquest({
        url: '/index/plugin.orders/getDoctors',
        method: 'GET',
        data: {
          shop_id: this.shopId
        }
      });
      if (res.data.code === 200) {
        this.doctors = res.data.data;
      } else {
        uni.showToast({
          title: '获取医生列表失败',
          icon: 'none',
          duration: 2000
        });
      }
    },
    async searchMember() {
      const res = await this.$myRuquest({
        url: '/index/plugin.orders/getMemberByCard',
        method: 'GET',
        data: {
          card_number: this.memberCard
        }
      });
      if (res.data.code === 200) {
        this.memberName = res.data.data.name;
      } else {
        uni.showToast({
          title: '没有找到相关会员',
          icon: 'none',
          duration: 2000
        });
      }
    },
    filterDrugs() {
      const query = this.searchQuery.toLowerCase();
      this.filteredDrugs = this.drugs.filter(drug =>
        drug.product_name.toLowerCase().includes(query) ||
        (drug.short_code && drug.short_code.toLowerCase().includes(query))
      );
    },
    addDrugToPrescription(drug) {
      const prescriptionItem = this.prescription.find(item => item.id === drug.id);
      if (!prescriptionItem) {
        this.prescription.push({
          ...drug,
          quantity: 1,
          total: drug.retail_price
        });
      }
    },
    removeDrugFromPrescription(drug) {
      const index = this.prescription.findIndex(item => item.id === drug.id);
      if (index !== -1) {
        this.prescription.splice(index, 1);
      }
    },
    clearPrescription() {
      this.prescription = [];
    },
    increaseQuantity(item) {
      item.quantity++;
      item.total = (item.retail_price * item.quantity).toFixed(2);
    },
    decreaseQuantity(item) {
      if (item.quantity > 1) {
        item.quantity--;
        item.total = (item.retail_price * item.quantity).toFixed(2);
      }
    },
    openSubmitPopup() {
      this.$refs.submitPopup.open();
    },
    closeSubmitPopup() {
      this.$refs.submitPopup.close();
    },
    async submitPrescription() {
        const orderData = {
          shop_id: this.shopId,
          order_number: `ORD-${Date.now()}`,
          order_time: new Date().toISOString(),
          order_type: '药方',
          member_card: this.memberCard,
          member_name: this.memberName,
          total_amount: this.totalAmount,
          discount_amount: 0,
          received_amount: this.totalAmount,
          operator: this.doctors.find(doctor => doctor.id === this.selectedDoctorIndex) ? this.doctors.find(doctor => doctor.id === this.selectedDoctorIndex).name : '',
          note: this.description,
          main_account_id: this.mainAccountId,
          doctor_id: this.selectedDoctorIndex,
          member_id: this.memberCard, // Assuming member_id is the card number here
          case_history: this.description,
          case_image: '', // Assuming case_image is empty here
          items: this.prescription // Ensure this is correctly populated
        };
    
        console.log('Order Data:', orderData); // Debugging line
    
        const res = await this.$myRuquest({
          url: '/index/plugin.orders/insertOrder',
          method: 'POST',
          data: orderData
        });
    
        if (res.data.code === 200) {
          uni.showToast({
            title: '药方提交成功',
            icon: 'success',
            duration: 2000
          });
          this.clearPrescription();
          this.fetchDrugs();
          this.closeSubmitPopup();
        } else {
          uni.showToast({
            title: res.data.message,
            icon: 'none',
            duration: 2000
          });
        }
      },
    checkLoginStatus() {
      const token = uni.getStorageSync('token');
      if (token) {
        this.userInfo = JSON.parse(uni.getStorageSync('userInfo'));
        this.shopId = this.userInfo.shop_id; // Assuming shop_id is part of userInfo
        this.fetchDoctors();
        this.fetchDrugs();
      } else {
        this.userInfo = {};
        this.$router.push('/pages/login/login');
      }
    }
  },
  mounted() {
    this.checkLoginStatus();
  }
};
</script>

<style>
.container {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.popup-container {
  background: #fff;
  padding: 20px;
  border-radius: 5px;
  width: 300px;
}

.content {
  display: flex;
  flex: 1;
}

.input-field {
  flex: 1;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  outline: none;
}

.left-side {
  flex: 1;
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-right: 20px;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
}

.search-box {
  display: flex;
  margin-bottom: 20px;
}

.search-input {
  flex: 1;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px 0 0 4px;
  outline: none;
}

.picker {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 0 4px 4px 0;
  margin-left: 10px;
  background-color: #fff;
}

.search-button {
  background-color: #4cd964;
  color: white;
  border: none;
  padding: 10px 20px;
  cursor: pointer;
  border-radius: 4px;
  margin-left: 10px;
}

.search-button:hover {
  background-color: #45c853;
}

.drug-list {
  flex: 1;
  overflow-y: auto;
}

.drug-item {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  margin-bottom: 10px;
  cursor: pointer;
  background-color: #f9f9f9;
}

.drug-item:hover {
  background-color: #4cd964;
  color: white;
}

.drug-name {
  font-size: 16px;
  font-weight: bold;
}

.drug-details {
  font-size: 14px;
  color: #666;
}

.right-side {
  flex: 1;
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  box-sizing: border-box;
}

.prescription-list {
  flex: 1;
  overflow-y: auto;
}

.prescription-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  margin-bottom: 10px;
  background-color: #f9f9f9;
}

.item-details {
  flex: 1;
}

.input-group {
  display: flex;
  align-items: center;
  margin-bottom: 5px;
}

.input-group label {
  width: 50px;
}

.item-controls {
  display: flex;
  gap: 5px;
}

.order-summary {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
  background-color: #f9f9f9;
  border-top: 1px solid #ddd;
  padding: 10px;
  border-radius: 4px;
}

.summary-item {
  font-size: 14px;
  color: #333;
}

.button-group {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
}

.clear-button,
.submit-button {
  background-color: #4cd964;
  color: white;
  border: none;
  padding: 8px 16px;
  cursor: pointer;
  border-radius: 4px;
  flex: 1;
  margin: 5px;
}

.clear-button:hover,
.submit-button:hover {
  background-color: #45c853;
}
</style>
